package org.budo.xml.lexer.impl;

import java.util.LinkedList;
import java.util.List;

import org.budo.support.lang.util.StringUtil;
import org.budo.xml.lexer.XmlLexer;
import org.budo.xml.lexer.pojo.XmlToken;
import org.budo.xml.lexer.pojo.XmlToken.Type;

/**
 * @author lmw
 */
public class BudoXmlLexer implements XmlLexer {
    private static final String[] KEY_WORDS = { //
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", //
            "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">" //
    };

    @Override
    public List<XmlToken> tokens(String source) {
        List<XmlToken> tokens = new LinkedList<XmlToken>();

        String tmp = "";

        for (int i = 0; i < source.length(); i++) {
            for (String keyWord : KEY_WORDS) { // 匹配关键字
                String value = StringUtil.substring(source, i, i + keyWord.length());
                if (keyWord.equals(value)) {
                    tokens.add(new XmlToken(Type.KEY_WORD, value));
                    i += keyWord.length();
                    continue;
                }
            }

            char ch = source.charAt(i);

            if ('<' == ch) {
                tokens.add(new XmlToken(Type.LT, ch + ""));
                tmp = "";
                continue;
            }

            if ('>' == ch) {
                tokens.add(new XmlToken(Type.OTHER, tmp));
                tokens.add(new XmlToken(Type.GT, ch + ""));
                tmp = "";
                continue;
            }

            if ('=' == ch) {
                tokens.add(new XmlToken(Type.STRING, tmp));
                tokens.add(new XmlToken(Type.EQ, ch + ""));
                tmp = "";
                continue;
            }

            // 遇到空格 收集到关键字
            if (' ' == ch) {
                tokens.add(new XmlToken(Type.OTHER, tmp));
                tokens.add(new XmlToken(Type.SPACE, " ")); // 空格
                tmp = "";
                continue;
            }

            // 暂存
            tmp += ch;
        }

        return tokens;
    }
}